<template>
	<u-picker closeOnClickOverlay @cancel="cancel" :loading="loading" :show="show" ref="uPicker"
		:columns="addresList" @confirm="addrConfirm" keyName="region_name" @change="changeHandler"></u-picker>
</template>

<script>
	import common from '@/api/common.js';
	export default {
		name: 'areaPicker',
		props: {
			show: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				addresList: [],
				loading: false,
				addrIndex: 0
			}
		},
		mounted() {
			this.getProvice()
		},
		methods: {
			cancel() {
				this.$emit('cancel')
			},
			addrConfirm({
				value
			}) {
				let provice, city, district
				let proviceName, cityName, districtName
				provice = value[0].region_id
				city = value[1] ? value[1].region_id : 0
				district = value[2] ? value[2].region_id : 0
				proviceName = value[0].region_name
				cityName = value[1] ? value[1].region_name : ''
				districtName = value[2] ? value[2].region_name : ''
				this.$emit('addrConfirm', {
					provice,
					city,
					district
				}, {
					proviceName,
					cityName,
					districtName
				})
			},
			changeHandler(e) {
				const {
					columnIndex,
					value,
					values, // values为当前变化列的数组内容
					index,
					// 微信小程序无法将picker实例传出来，只能通过ref操作
					picker = this.$refs.uPicker
				} = e
				switch (columnIndex) {
					case 0:
						this.loading = true
						this.getCity(value[0].region_id)
						this.addrIndex = index
						break
					case 1:
						this.loading = true
						this.getDistrict(value[1].region_id)
						break
				}
			},
			//区
			async getDistrict(pid) {
				const res = await common.getArea({
					pid: pid
				})
				this.$refs.uPicker.setColumnValues(2, res.data)
				this.loading = false
			},
			//市
			async getCity(pid,index) {
				const res = await common.getArea({
					pid: pid
				})
				if(!res.data.length){
					this.loading = false
					this.$refs.uPicker.setColumnValues(1, [])
					this.$refs.uPicker.setColumnValues(2, [])
					return
				}
				this.$refs.uPicker.setColumnValues(1, res.data)
				this.getDistrict(res.data[0].region_id)
				console.log('市')
			},
			//省
			async getProvice(pid = -1) {
				const res = await common.getArea({
					pid: pid
				})
				this.addresList.push(res.data)
				this.getCity(this.addresList[0][this.addrIndex].region_id)
			},
		}
	}
</script>

<style lang="scss">
	input{
		background: #fff;
	}
</style>